

import java.io.IOException;
import java.net.Socket;
import java.util.Date;

/**
 * ����� ��� ���������� ������
 * 1) ����� ��������������
 * 2) ���� �������������� ������, �� ������� ����� �������
 * 3) ��� ������� ��������� ����������
 * 	3.1) ���� ��������� ���� - �������� ����
 * 	3.2) ���� ��������� ��������� - �������� ��������� ��������
 * 
 * дывоадыволапж
 */
public class ChatThread implements Runnable {

    private Socket socket;
	@SuppressWarnings("unused")
	private final int id;
	private String login;
	private ChatServer chatServer;
	
	public ChatThread(ChatServer chatServer, Socket socket, int id) {
		this.socket = socket;
		this.id = id;
		this.chatServer = chatServer;
	}

	public Socket getSocket() {
		return socket;
	}

	public String getLogin() {
		return login;
	}
	
	@Override
	public void run() {
		execute();
	}

	public void execute(){
		try {
			ChatAccessService chatAccessService = new ChatAccessService(socket);
			
			//[ek] TODO try to refactor to if(_NOT_ checkAuth) then _some error_ form - it's more readable
			while(!chatAccessService.login()) {
				
			} 
			
				login = chatAccessService.getLogin();
				new ChatMessageService("server > " + this.getLogin() + " joined chat").sendToGroup(chatServer.getChatThreads().values());
				chatServer.consoleMessage("server > " + this.getLogin() + " joined chat", new Date());
				chatServer.addChatThread(this);

				new ChatMessageService("server > Hi, " + login).send(socket);
				//[ek] XXX a very, VERY lot of new Message. You'll kill the GC.
				ChatMessageService chatMessageService = null;
				while (!socket.isClosed()) {
					//[ek] XXX a very, VERY lot of new Message. You'll kill the GC.
					chatMessageService = new ChatMessageService(this);
					chatMessageProceed(socket, chatServer, chatMessageService);
				
			}
			
		} catch (IOException e) {
			chatServer.consoleMessage(login + " connection lost", new Date());
			//e.printStackTrace();
		}
	}
	
	private synchronized void chatMessageProceed(Socket socket, ChatServer chatServer, ChatMessageService chatMessageService) throws IOException {
		if (socket.isClosed()) {
			chatServer.consoleMessage("server > " + login + " leaved chat", new Date());
			chatServer.removeChatThread(this);
		} else {
			chatMessageService.sendToGroup(chatServer.getChatThreads().values());
			chatServer.consoleMessage(chatMessageService.getContent(), new Date());
		}
	}
	
}
